package com.example.demo.controller;

import com.example.demo.model.Book;
import com.example.demo.model.PageRequest;
import com.example.demo.model.PageResponse;
import com.example.demo.model.Resp;
import com.example.demo.service.BookinfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookinfoService bookinfoService;
    //得到页面图书信息
    @RequestMapping("/getlist")
    public PageResponse<Book> getList(PageRequest pageRequest) {
        log.info("获取指定页面的图书 pageRequest"+pageRequest.toString());
        return bookinfoService.getBookList(pageRequest);
    }

    //新增图书
    @RequestMapping("addbook")
    public Resp addBook(Book book) {
        log.info("插入图书 book:"+book.toString());
        if (book.getBookName() == null ||
            book.getCount() == null ||
            book.getAuthor() == null ||
            book.getPrice() == null ||
            book.getPublish() == null) {
            return Resp.fail("参数不能为空");
        }
        return Resp.seccess(bookinfoService.addBook(book));
    }

    //删除图书
    @RequestMapping("/deletebook")
    public Resp<Boolean> deleteBook(Book book) {
        log.info("删除图书 book:"+book.toString());
        if (book.getId() < 0) {
            return Resp.fail("非法的参数");
        }
        return Resp.seccess(bookinfoService.deleteBook(book));
    }
    //批量删除
    @RequestMapping("/deletebooks")
    public Resp<Boolean> deletebooks(@RequestParam("ids") List<Integer> ids) {
        log.info("批量删除图书 book:{}", ids);
        if (ids == null || ids.isEmpty()) {
            return Resp.fail("非法的参数");
        }
        for (int i = 0; i < ids.size(); i++) {
            if (ids.get(i) < 0) {
                return Resp.fail("非法的参数");
            }
        }
        return Resp.seccess(bookinfoService.deleteBooks(ids));
    }
    //根据id查找图书
    @RequestMapping("getbyid")
    public Book getbyid(Integer id) {
        log.info("根据id查找图书 id:"+id);
        return bookinfoService.getBookById(id);
    }
    //修改图书
    @RequestMapping("updatebook")
    public Resp<Boolean> updateBook(Book book) {
        log.info("更新图书 book："+book.toString());
        if (book.getId() < 0 ||
                book.getBookName() == null ||
                book.getCount() == null || book.getCount() < 0 ||
                book.getAuthor() == null ||
                book.getPrice() == null || book.getPrice().compareTo(new BigDecimal(0)) < 0 ||
                book.getPublish() == null) {
            return Resp.fail("参数不能为空或含有非法参数");
        }
        return Resp.seccess(bookinfoService.updateBook(book));
    }
}
